package com.iss.yunpan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iss.yunpan.entity.FileContent;
import com.iss.yunpan.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FileController {

    @Autowired
    private FileService service;

    @RequestMapping("getAllFile")
    @ResponseBody//object是所有类型中的父类。只要不是form表单提交的，都需要加本行
    public Map<String, Object> getAllFile(String id, int page, int limit, String parentId) {  //修改？
        System.out.println(id);
        if (parentId == null) {
            parentId = "0";
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(page, limit);
        List<FileContent> list = service.getAllFile(id);                              //(id,parentId)
        PageInfo<FileContent> pageInfo = new PageInfo<FileContent>(list);
        System.out.println(pageInfo);
        map.put("code", 0);//详见layui数据表格文档示例！
        map.put("msg", "");
        map.put("count", pageInfo.getTotal());//获取总个数
        map.put("data", pageInfo.getList());//最终的数据
        return map;
    }
    @RequestMapping("getAllFile1")
    @ResponseBody//object是所有类型中的父类。只要不是form表单提交的，都需要加本行
    public Map<String, Object> getAllFile1(String id, int page, int limit,String parentId){  //修改？
        System.out.println(id);
        if(parentId==null) {
            parentId = "0";
        }
        Map<String, Object>map=new HashMap<>();
        PageHelper.startPage(page,limit);
        List<FileContent> list=service.getAllFile1(id);                              //(id,parentId)
        PageInfo<FileContent> pageInfo =new PageInfo<FileContent>(list);
        System.out.println(pageInfo);
        map.put("code",0);//详见layui数据表格文档示例！
        map.put("msg","");
        map.put("count",pageInfo.getTotal());//获取总个数
        map.put("data", pageInfo.getList());//最终的数据
        return map;
    }

    @ResponseBody
    @RequestMapping("download")
    public ResponseEntity<byte[]> download(String fileAbsolute, HttpServletRequest request, HttpServletResponse response)throws IOException {
        String downLoadPath = request.getServletContext().getRealPath("uploadfiles");
        // 设置下载文件使用的报头
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(fileAbsolute));
        byte[] newByte = service.download(fileAbsolute);
        return new ResponseEntity<byte[]>(newByte, HttpStatus.OK);
    }

    /**
     * 下载保存时中文文件名的字符编码转换方法
     */
    public String toUTF8String(String str)
    {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode 码值为 0 ～ 255 时，不做处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                // 转换 UTF-8 编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }


    @RequestMapping("insertFolder")
    @ResponseBody   //ajax要加上这玩意儿！
    public Map<String,Object>insertFolder(String fileName,Integer parentId) {
        Map<String, Object> map = new HashMap<>();
        if (parentId == null) {
            parentId = 0;
        }
        if (fileName.equals("")) {
            map.put("msg", "文件夹名称不能为空");
        } else {
            boolean flag = service.checkFileContent(fileName, parentId);
            if (flag) {
                map.put("msg", "文件夹名字不能重复！");
            } else {
                service.insertFolder(fileName, parentId);
                map.put("code", 1);
                map.put("msg", "新建文件夹成功");

            }
        }
        return map;
    }


    @RequestMapping("uploadFile")
    @ResponseBody//空跳转
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, String parentId) throws IOException {//map为springmvc上传内容类型,获取上传文件file信息，“file”为底层所传
        Map<String, Object> map = new HashMap<>();
        if (parentId == null) {
            parentId = "0";//先验证
        }
        if (file != null) {
            String fileName = file.getOriginalFilename();//获取文件名
            InputStream input = file.getInputStream();//获取文件内容，该两项为向底层所传内容
            service.uploadFile(fileName, input, parentId);//传此3个参数
            map.put("code", 0);//使判断上传成功
            map.put("msg", "上传成功");
        } else {//file==null
            map.put("meg", "文件不能为空");
        }
        return map;

    }

    @RequestMapping("renameFile")
    @ResponseBody   //ajax要加上这玩意儿！
    public Map<String,Object>renameFile( String newFileName,String fileAbsolute,Integer id) throws IOException {
        Map<String, Object>map=new HashMap<>();
        String  a="" ;
        if(fileAbsolute.contains("/"))
        { a= fileAbsolute.substring(0,fileAbsolute.lastIndexOf("/"));}
        String  newFileAbsolute = a + newFileName;
        System.out.println(newFileName);
        service.checkFileName(id,newFileName,newFileAbsolute,fileAbsolute);//方法自行添加上去的
        map.put("code",0);
        //   map.put("msg", "文件重命名成功！");
        return  map;
    }


    @RequestMapping("getFile")
    @ResponseBody
    public Map<String, String> getFile(String fileAbsolute){
        String  url =service.getFile(fileAbsolute);
        Map<String,String> map = new HashMap<>();
        map.put("url",url);
        return map;
    }
    @RequestMapping("deleteFile")
    @ResponseBody//空跳转
    public Map<String,Object> deleteFile(String fileName, Integer parentId) throws IOException {//map为springmvc上传内容类型,获取上传文件file信息，“file”为底层所传
        Map<String, Object>map=new HashMap<>();
        service.deleteFile(fileName);
        map.put("code", 0);
        map.put("msg", "删除成功");
        return map;
    }
    @RequestMapping("restoreFile")
    @ResponseBody//空跳转
    public Map<String,Object> restoreFile(String fileName, Integer parentId) throws IOException {//map为springmvc上传内容类型,获取上传文件file信息，“file”为底层所传
        Map<String, Object>map=new HashMap<>();
        service.restoreFile(fileName);
        map.put("code", 0);
        map.put("msg", "恢复成功");
        return map;
    }

    @RequestMapping("delete")
    @ResponseBody//空跳转
    public Map<String,Object> delete(String fileName, Integer parentId) throws IOException {//map为springmvc上传内容类型,获取上传文件file信息，“file”为底层所传
        Map<String, Object>map=new HashMap<>();
        service.delete(fileName);
        map.put("code", 0);
        map.put("msg", "彻底删除成功");
        return map;
    }

}
